import React, { useCallback, useEffect, useRef, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { Dialog, Drawer } from '@alifd/next';
import { t } from '@lingui/macro';
import { DialogProps } from '@alifd/next/types/dialog';

interface MapModelProps extends DialogProps {
  coord?: { lng: string; lat: string };
  onPick: (coord?: string) => void;
}

export default observer((props: MapModelProps) => {
  const { coord, visible, onPick, ...otherProps } = props;
  const [loc, setLoc] = React.useState({ lat: Number, lng: Number });
  const ref = useRef();
  const [baseUrl, setBaseUrl] = useState('');
  // https://lbs.qq.com/webApi/component/componentGuide/componentPicker

  useEffect(() => {
    if (visible) {
      (async () => {
        const key = await globalThis._mapsKey();
        const base = `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=${key}&referer=travel_uat`;
        setBaseUrl(base);
      })();
    }
  }, [visible]);

  const eventListener = useCallback((event) => {
    // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
    const loc = event.data;
    if (loc && loc.module === 'locationPicker') {
      // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
      setLoc(loc);
    }
  }, []);

  useEffect(() => {
    window.addEventListener('message', eventListener, false);
    return () => {
      window.removeEventListener('message', eventListener);
    };
  }, []);

  useEffect(() => {
    if (visible && ref.current) {
      ref.current.src = `${baseUrl}&coord=${coord}`;
    }
  }, [visible, coord]);

  const handleOK = (e) => {
    if (Object.keys(loc).length) {
      const value = `${loc.latlng.lng},${loc.latlng.lat}`;
      onPick(value);
    } else {
      onPick();
    }
  };
  return (
    <>
      <Dialog
        v2
        title={t`选择地点`}
        centered
        width="70%"
        height="90vh"
        onOk={handleOK}
        visible={visible}
        {...otherProps}
      >
        <iframe
          ref={ref}
          id="mapPage"
          title="map"
          width="100%"
          style={{ border: 0, height: 'calc(90vh - 85px - 52px)' }}
          src={`${baseUrl}&coord=${coord}`}
        />
      </Dialog>
    </>
  );
});
